package com.rgst.controller;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import com.rgst.comm.SearchParam;
import com.rgst.dao.entity.User;
import com.rgst.dao.repository.UserRepository;
import com.rgst.dto.Result;
import com.rgst.utils.Md5SaltTool;

/**
 * Created by tancw on 2019/12/8.
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("list")
    public ModelAndView list() {
        ModelAndView view = new ModelAndView();
        view.setViewName("rgst/user/list");
        return view;
    }

    @ResponseBody
    @RequestMapping("list-data")
    public Page<User> listData(SearchParam sp) {
        Pageable pageable = sp.getPageable(new Sort(Sort.Direction.ASC, "id"));
        ExampleMatcher matcher = ExampleMatcher.
                matching()
                .withMatcher("realname", ExampleMatcher.GenericPropertyMatchers.startsWith())
                .withMatcher("mobile", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("idcard", ExampleMatcher.GenericPropertyMatchers.contains())
                .withIgnorePaths("id", "sex", "weChatNo", "status", "createTime", "address", "remark", "password");

        Page<User> users = userRepository.findAll(sp.getParam(User.class, matcher), pageable);
        return users;
    }

    @ResponseBody
    @RequestMapping("resetPwd")
    public Result resetPwd(Long userId) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        Assert.notNull(userId, "param error");
        Optional<User> op = userRepository.findById(userId);
        if (op.isPresent()) {
            User user = op.get();
            String mobile = user.getMobile();
            String initPwd = StringUtils.substring(mobile, mobile.length() - 4);
            user.setPassword(Md5SaltTool.getEncryptedPwd(initPwd));
            userRepository.save(user);
        }
        return Result.success("重置成功");
    }
}
